using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Voodoo.Sauce.Core;
using Voodoo.Sauce.Internal.Analytics;
using Voodoo.Sauce.Internal.Analytics.VoodooAnalytics._3rdParty.Common;

namespace Voodoo.Analytics
{
	internal static class AnalyticsApi
	{
		private const string TAG = "Analytics - Sender";

		private static HttpClient _client;

		private static string AnalyticsGatewayUrl { get; set; }

		public static string ProxyServer { get; set; }

		private static HttpClient DefaultVoodooAnalyticsHttpClient()
		{
			if (_client == null)
			{
				_client = new HttpClient(new AnalyticsHttpLoggingClientHandler((string.IsNullOrEmpty(ProxyServer) ? null : new HttpClientHandler
				{
					Proxy = new VoodooWebProxy(ProxyServer),
					UseProxy = true
				}) ?? new HttpClientHandler()));
			}
			return _client;
		}

		internal static void SetAnalyticsGatewayUrl(string url)
		{
			AnalyticsGatewayUrl = url;
		}

		internal static void SetHttpClient([CanBeNull] HttpClient httpClient)
		{
			_client = httpClient;
		}

		internal static async void SendEvents(List<string> events, string bundleId, Action<bool, HttpStatusCode?> complete)
		{
			AnalyticsLog.Log("Analytics - Sender", "Send " + events.Count + " event(s)");
			StringContent stringContent = new StringContent("[" + string.Join(",", events) + "]");
			stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
			stringContent.Headers.Add("Charset", "UTF-8");
			stringContent.Headers.Add("X-Voodoo-App", bundleId);
			try
			{
				HttpResponseMessage httpResponseMessage = await DefaultVoodooAnalyticsHttpClient().PostAsync(AnalyticsGatewayUrl, stringContent);
				AnalyticsLog.Log("Analytics - Sender", "Response: " + httpResponseMessage);
				complete(httpResponseMessage.IsSuccessStatusCode, httpResponseMessage.StatusCode);
				if (httpResponseMessage.IsSuccessStatusCode)
				{
					AnalyticsLog.Log("Analytics - Sender", "Successfully pushed " + events.Count + " events");
					AnalyticsEventLogger.GetInstance().LogEventsSentSuccessfully(events);
				}
				else
				{
					AnalyticsLog.Log("Analytics - Sender", "Error when sending events: " + httpResponseMessage.StatusCode.ToString() + " " + httpResponseMessage.ReasonPhrase);
					string error = httpResponseMessage.Content?.ReadAsStringAsync().Result ?? httpResponseMessage.ReasonPhrase;
					AnalyticsEventLogger.GetInstance().LogEventsSentError(events, error);
				}
				httpResponseMessage.Dispose();
			}
			catch (Exception ex)
			{
				if (!(ex is HttpRequestException) && !(ex is WebException) && !(ex is TaskCanceledException))
				{
					VoodooSauceCore.GetCrashReport().LogException(ex);
				}
				AnalyticsEventLogger.GetInstance().LogEventsSentError(events, ex.ToString());
				complete(arg1: false, null);
			}
		}
	}
}
